use crypto_hash::*;
use rsa::{RSAPrivateKey, RSAPublicKey, PaddingScheme, PublicKey};
use rand::rngs::OsRng;
use std::error::Error;

const ARITHMETIC: Algorithm = Algorithm::SHA512;

pub fn encrypt_un_back(data: &[u8]) -> String {
    hex_digest(ARITHMETIC, data)
}

/// RSA加密算法对象
struct Rsa {
    rng: OsRng,
}

impl Rsa {
    pub fn new() -> Self {
        Rsa {
            rng: OsRng::default(),
        }
    }
}

impl Rsa {
    /// 获取公钥和私钥
    pub fn get_keys(&mut self) -> (RSAPrivateKey, RSAPublicKey) {
        let private_key = RSAPrivateKey::new(&mut self.rng, 2048).unwrap();
        let public_key = RSAPublicKey::from(&private_key);
        (private_key, public_key)
    }

    /// 通过私钥进行加密
    pub fn decrypt(&mut self, public_key: &RSAPublicKey, data: &[u8]) -> String {
        let padding = PaddingScheme::new_pkcs1v15_encrypt();
        let vec = public_key.encrypt(&mut self.rng, padding, data).unwrap();
        String::from_utf8(vec).unwrap()
    }

    /// 通过私钥进行解密
    pub fn encrypt(&mut self, private_key: &RSAPrivateKey, data: &[u8]) -> String {
        let padding = PaddingScheme::new_pkcs1v15_encrypt();
        let vec = private_key.decrypt(padding, data).unwrap();
        String::from_utf8(vec).unwrap()
    }
}



